<?php
namespace api\modules\v1\models\shop;

use api\modules\v1\models\user\User;
use common\models\Functions;
use common\models\Status;
use Yii;
use yii\base\Exception;

class GoodsCommentRelation extends \common\models\shop\GoodsCommentRelation
{
    /**
     * 点赞评论
     * @return array
     */
    public function like() {
        $trans = static::getDb()->beginTransaction();

        try {
            $userInfo = (new User()) -> checkUser();

            $commentId = Yii::$app->request->post('comment_id','');
            if (!$commentId) {
                throw new Exception('参数错误！');
            }

            $where['is_delete'] = Status::COMMON_IS_NOT_DELETE;
            $where['id'] = $commentId;
            $info = GoodsComment::getOneByWhere($where);
            if (!$info) {
                throw new Exception('评论不存在！');
            }

            $data['comment_id'] = $commentId;
            $data['user_id'] = $userInfo['id'];
            $data['type'] = Status::CIRCLE_USER_RELATION_TYPE_LIKE;
            $check = static::getOneByWhere($data);
            if (!$check) {
                $data['create_time'] = date('Y-m-d H:i:s');
                $res = static::insertData($data);
                if ($res === false) {
                    throw new Exception('操作失败！');
                }

                $handleName = '点赞';

                $res = GoodsComment::updateAllCounters(['like_num' => 1], ['id' => $commentId]);
                if ($res === false) {
                    throw new Exception('操作失败！');
                }

                $likeNum = $info['like_num'] + 1;
            } else {
                $res = static::deleteAll(['id' => $check['id']]);
                if ($res === false) {
                    throw new Exception('操作失败！');
                }
                $handleName = '取消点赞';

                $res = GoodsComment::updateAllCounters(['like_num' => -1], ['id' => $commentId]);
                if ($res === false) {
                    throw new Exception('操作失败！');
                }
                $likeNum = $info['like_num'] - 1;
            }
            $return['like_num'] = (int) $likeNum;

            $trans->commit();
            return Functions::formatRestAPI(0, $handleName.'成功',$return);
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }


}
